const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const mongoose = require('../db');

const JWT_SECRET = 'lowcode_secret';

const userSchema = new mongoose.Schema({
  user_id: { type: String, unique: true, required: true },
  username: { type: String, unique: true, required: true },
  real_name: String,
  phone: { type: String, unique: true, required: true },
  gender: { type: String, default: '未知' },
  password: { type: String, required: true },
  role: { type: String, default: 'user' }
});

const User = mongoose.model('User', userSchema);

exports.register = async (username, password, real_name, phone, gender) => {
  const userByUsername = await User.findOne({ username });
  if (userByUsername) return { success: false, message: '用户名已存在' };
  const userByPhone = await User.findOne({ phone });
  if (userByPhone) return { success: false, message: '手机号已存在' };
  const hash = await bcrypt.hash(password, 10);
  const user = new User({
    user_id: phone,
    username,
    real_name,
    phone,
    gender: gender || '未知',
    password: hash,
    role: 'user',
  });
  await user.save();
  return { success: true };
};

exports.login = async (username, password) => {
  const user = await User.findOne({ username });
  if (!user) return { success: false, message: '用户不存在' };
  const match = await bcrypt.compare(password, user.password);
  if (!match) return { success: false, message: '密码错误' };
  const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '5m' });
  return { success: true, token };
};

exports.verifyToken = (token) => {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch {
    return null;
  }
};

exports.getAllUsers = async () => {
  return User.find({}, { username: 1, real_name: 1, phone: 1, gender: 1, role: 1, _id: 0 });
};

// 实时校验手机号唯一性
exports.checkPhone = async (phone) => {
  return !!(await User.findOne({ phone }));
};

// 实时校验用户名唯一性
exports.checkUsername = async (username) => {
  return !!(await User.findOne({ username }));
};

exports.getUserByUsername = async (username) => {
  return User.findOne({ username });
};

exports.signToken = (user) => {
  return jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '5m' });
}; 